package com.videoweb.controller;

import com.videoweb.model.Comment;
import com.videoweb.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.ArrayList;

@RestController
@RequestMapping("/api/comments")
@CrossOrigin
public class CommentController {
    @Autowired
    private CommentService commentService;
    
    @PostMapping
    public ResponseEntity<Comment> createComment(
            @RequestParam Long videoId,
            @RequestParam String content) {
        
        // 获取当前登录用户信息
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth == null || !auth.isAuthenticated() || "anonymousUser".equals(auth.getPrincipal())) {
            return ResponseEntity.status(401).build(); // 未认证用户不能发表评论
        }
        
        String commenter = auth.getName(); // 使用登录用户名作为commenter
        Comment comment = commentService.createComment(videoId, content, commenter);
        return ResponseEntity.ok(comment);
    }
    
    @GetMapping("/video/{videoId}")
    public ResponseEntity<List<Comment>> getCommentsByVideoId(@PathVariable Long videoId) {
        try {
            List<Comment> comments = commentService.getCommentsByVideoId(videoId);
            return ResponseEntity.ok(comments != null ? comments : new ArrayList<>());
        } catch (Exception e) {
            return ResponseEntity.ok(new ArrayList<>()); // 返回空列表而不是错误
        }
    }
}
